package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.mapper.BrandMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import sun.util.locale.LanguageTag;
import tk.mybatis.mapper.entity.Example;

import javax.persistence.Id;
import java.util.List;

/**
 * @author jinpei
 * @version v1.0
 * @date 2019/5/6 15:41
 * @description TODO
 **/
@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    public PageResult<BrandDTO> queryBrandByPage(Integer page, Integer rows, String sortBy, Boolean desc, String key) {
        // 分页
        PageHelper.startPage(page, rows);

        // 过滤条件
        Example example= new Example(Brand.class);
        if (StringUtils.isNotBlank(key)) {
            example.createCriteria().orLike("name", "%" + key + "%")
                    .orEqualTo("letter", key.toUpperCase());
        }

        // 排序
        if (StringUtils.isNotBlank(sortBy)) {
            String orderByClause = sortBy + (desc ? " DESC" : " ASC");
            example.setOrderByClause(orderByClause);
        }

        // 查询
        List<Brand> brandList = brandMapper.selectByExample(example);

        // 健壮性判断
        if (CollectionUtils.isEmpty(brandList)) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }

        // 封装结果
        PageInfo<Brand> brandPageInfo = new PageInfo<>(brandList);

        // 转为BrandInfo
        List<BrandDTO> brandDTOList = BeanHelper.copyWithCollection(brandList, BrandDTO.class);

        // 返回结果
        return new PageResult<>(brandPageInfo.getTotal(), brandDTOList);
    }

    public void saveBrand(BrandDTO brandDTO, List<Long> ids) {
        // 把DTO转换为PO
        Brand brand = BeanHelper.copyProperties(brandDTO, Brand.class);
        // 新增品牌
        int count = brandMapper.insertSelective(brand);
        if (count != 1) {
            // 新增失败，抛出异常
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        // 新增中间表
        count = brandMapper.insertCategoryBrand(brand.getId(), ids);
        if (count != ids.size()) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    @Transactional
    public void updateBrand(BrandDTO brandDTO, List<Long> ids) {
        Brand brand = BeanHelper.copyProperties(brandDTO, Brand.class);
        // 修改品牌
        int count = brandMapper.updateByPrimaryKeySelective(brand);
        if(count != 1){
            // 更新失败，抛出异常
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        // 删除中间表数据
        brandMapper.deleteCategoryBrand(brand.getId());

        // 重新插入中间表数据
        count = brandMapper.insertCategoryBrand(brand.getId(), ids);
        if(count != ids.size()){
            // 新增失败，抛出异常
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    public BrandDTO queryById(Long id) {
        Brand brand = brandMapper.selectByPrimaryKey(id);
        if (brand == null) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyProperties(brand, BrandDTO.class);
    }

    public List<BrandDTO> queryBrandByCategoryId(Long id) {
        List<Brand> brandList = brandMapper.queryBrandByCategoryId(id);
        if (CollectionUtils.isEmpty(brandList)) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(brandList, BrandDTO.class);
    }

    public List<BrandDTO> queryBrandByIds(List<Long> idList) {
        List<Brand> brandList = brandMapper.selectByIdList(idList);
        if (CollectionUtils.isEmpty(brandList)) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(brandList, BrandDTO.class);
    }
}
